package com.songyz.image.compress.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.function.Consumer;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.songyz.image.compress.dto.ImageCompressDTO;
import com.songyz.image.compress.dto.ImageCompressParam;
import com.songyz.image.compress.enums.Compress;

public class CompressUtils {

    private static Logger logger = LoggerFactory.getLogger(CompressUtils.class);

    private static String tmpdir;
    public static final String FOLD = "compress\\";

    static {
        tmpdir = System.getProperty("java.io.tmpdir");
        System.out.println(tmpdir);
    }

    public static Future<ImageCompressDTO> startCompress(ImageCompressParam param, String sessionId, String fileName,
            Consumer<ImageCompressDTO> consumer) {

        return ExecPool.submit(() -> {
            logger.info("开始压缩 :{},压缩参数:{}", fileName, param);

            File source = new File(getSourcePath(sessionId, fileName));
            File target = new File(getTargetPath(sessionId, fileName));
            try {
                // 开始压缩
                ThumbnailsUtils.compress(param, source, target);

                // 图片对象
                BufferedImage sourceImage = ImageIO.read(source);
                BufferedImage targetImage = ImageIO.read(target);

                ImageCompressDTO file = new ImageCompressDTO(fileName, Compress.SUCCESS);

                file.setFileSize(source.length(), target.length());

                file.setWidthAndHeight(sourceImage.getWidth() + "x" + sourceImage.getHeight());
                file.setCompressWidthAndHeight(targetImage.getWidth() + "x" + targetImage.getHeight());

                consumer.accept(file);

                return file;
            }
            catch (IOException e) {
                logger.error(e.getMessage(), e);
                return null;
            }
        });

    }

    public static String getSourcePath(String sessionId, String fileName) {
        return tmpdir + FOLD + sessionId + "\\" + fileName;
    }

    public static String getTargetPath(String sessionId, String fileName) {
        return tmpdir + FOLD + sessionId + "\\compress" + fileName;
    }

    public static String getSessionPath(String sessionId) {
        return tmpdir + FOLD + sessionId + "\\";
    }

}
